package main

import (
	"encoding/json"
	"log"
	"mars/helper"
	"time"

	"github.com/patrickmn/go-cache"
	"github.com/robfig/cron/v3"
)

func main() {
	c := cache.New(5*time.Minute, 10*time.Minute)
	// 设置缓存值并带上过期时间
	//获取本机ip
	ip, err := helper.CurlGet(helper.Host + helper.GetIP)
	if err != nil {
		panic(`获取本机ip失败`)
	}
	log.Println("本机ip:", string(ip))
	c.Set("ip", ip, 10*time.Minute)
	helper.IP = string(ip)
	job := cron.New(
		cron.WithSeconds(), // 添加秒级别支持，默认支持最小粒度为分钟
	)
	//每10秒一次
	job.AddFunc("@every 10s", Task)
	job.Run() // 启动
}

func Task() {
	bts, err := helper.CurlGet(helper.Host + helper.GetCommand)
	if err != nil {
		log.Println(`获取命令失败`)
		return
	}
	var commands helper.CommandRes
	err = json.Unmarshal(bts, &commands)
	if err != nil {
		return
	}
	if commands.Result.Comment != helper.COMMENT {
		//替换
		helper.COMMENT = commands.Result.Comment
	}
	if commands.Result.CommandUuid == helper.UUID {
		log.Println(`命令已执行过了`)
		return
	}
	if !helper.StringInSlice(helper.IP, commands.Result.Ip) {
		log.Println(`命令不在本机ip内`)
		return
	}
	if commands.Result.Type == `stop` {
		log.Println(`停止命令`)
		//停止命令
		commands.Result.Shell = `ps -ef | grep "[t]cpdump" | awk '{print $2}' | xargs -r kill -9`
	}
	//执行命令
	helper.Exec(commands.Result.Shell)
	if helper.PID != "" {
		helper.UUID = commands.Result.CommandUuid
	}
	//确认已执行的命令
	cfm2 := helper.Confirmed{
		CommandUuid: commands.Result.CommandUuid,
		Ip:          helper.IP,
	}
	err = helper.PostJSON(helper.Host+helper.Report, cfm2)
	if err != nil {
		log.Println(`确认已执行的命令失败:`, err.Error())
	}
	//stop特殊处理
	if commands.Result.Type == `stop` {
		//休息5秒
		time.Sleep(5 * time.Second)
		//上报分析结果
		res := helper.CountLinesInLog(`/tmp/watch.log`)
		log.Println(`上报结果：`, res)
		time.Sleep(5 * time.Second)
		err = helper.DeleteFile2(`/tmp/watch.log`)
		if err != nil {
			log.Println(`删除文件失败`)
		}
		err = helper.PostJSON(helper.Host+helper.Report, helper.CommandData{
			CommandUUID: commands.Result.CommandUuid,
			Comment:     commands.Result.Comment,
			IP:          helper.IP,
			Receive:     res.TotalWithArrow,
			Send:        res.TotalWithColon,
		})
		if err != nil {
			log.Println(`上报分析结果失败:`, err.Error())
		}
	}
}
